var express = require('express');
var router = express.Router();
let DB = require("../tools/DB");
let md5 = require("md5");

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//登录界面
router.get("/login",(req,res)=>{
  res.render("login.ejs")
})

//注册界面
router.get("/register",(req,res)=>{
  res.render("register.ejs")
})

//登录验证
router.post("/dologin",async (req,res,next) => {
  let {username,password} = req.body;
  // 将用户输入的加密对比
  let newPwd = md5(password + "www");
  let a = await DB.query("select username,password from login where username=? and password=?",[username,newPwd]);
  console.log(a);
  if(a.length > 0){
    res.cookie("username",username,{signed:true});
    res.json({code:200,data:[],msg:"登录成功"});
    return;

  }else{
    res.json({code:208,data:[],msg:"账号或密码不正确"});
    return;

  }
  DB.close();
});
//注册验证
router.post("/doregister",async (req,res,next) => {
  let {username,password} = req.body;
  // 将用户密码加密后存入
  let newPwd = md5(password + "www");
  let a = await DB.query("select username,password from login where username=?",[username]);
  if(a.length <= 0){
    let b = await DB.query("insert into login(username,password) values(?,?)",[username,newPwd]);
    if(b.affectedRows > 0){
      res.json({code:200,data:[],msg:"注册成功"});
      return;
    }else{
        res.json({code:208,data:[],msg:"加入数据库失败"});
        return;

    }
  }else{
    res.json({code:208,data:[],msg:"用户名已使用"});
    return;

  }
})
router.get("/list",async (req,res)=>{
  let a = await DB.query("select id,username,password from login",[]);
  console.log(a);
  res.render("./list",{a});
})

router.get("/del",async (req,res)=>{
  let {username} = req.query;
  console.log(username);
  let a = await DB.query("delete from login where username=?",[username]);
  if(a.affectedRows > 0){
    res.json({code:200,data:[],msg:"删除成功"});
    return;
  }else{
      res.json({code:208,data:[],msg:"删除失败"});
      return;

  }
})


router.get("/ajax",(req,res)=>{
  res.json({
    code:200,
    data:["小明","小红"],
    msg:"学生数据获取成功"
  })
})

module.exports = router;
